<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/4/6
 * Time: 下午2:05
 */

namespace App\Busi\Traits;


use App\Exceptions\CategoryException;
use App\Exceptions\ErrorCode\CategoryError;
use App\Exceptions\ErrorCode\RoError;
use App\Exceptions\RoException;
use App\Models\Level;
use App\Models\Quota;
use App\Models\SecQualifyCategory;
use App\Models\SupQualifyCategory;

Trait QuotaTrait
{
    public function getQuotaByIdAndLevel($supcategory_id,$subcategory_id,$level){
        $where = [
            ["supcategory_id","=",$supcategory_id],
            ["subcategory_id","=",$subcategory_id],
            ["level","=",$level]
        ];
        $fields = ["desc","standrad","process","material"];
        $data = Quota::where($where)->select(["*"])->first();
        if(!$data){
            throw new CategoryException(CategoryError::CATEGORY_NOT_EXSITS);
        }
        $total_fee = 0;
        $data["items"] = $data->staffitems;
        $staff_fee = 0;
        $service_fee = 0;
        $achievement_fee = 0;
        foreach ($data["items"] as &$item){
            if($item["type"] == 0){
                $item["type"] = "人员费用";
                $staff_fee =  $staff_fee+floatval($item["fee_price"])*$item["fee_num"];
            }
            if($item["type"] == 1){
                $item["type"] = "服务费用";
                $service_fee = $service_fee+ floatval($item["fee_price"])*$item["fee_num"];
            }
            if($item["type"] == 2){
                $item["type"] = "业绩费用";
                $achievement_fee =$achievement_fee+floatval($item["fee_price"])*$item["fee_num"];
            }
//            $item["type"] = $item["type"] == 0 ? "人员费用":"服务费用";
            $item["item_total"] = floatval($item["fee_price"])*$item["fee_num"];
            $total_fee = $total_fee+$item["item_total"];
            unset($item["pivot"]);
            unset($item["sup_category_id"]);
            unset($item["sub_category_id"]);
            unset($item["level_id"]);
            unset($item["province_id"]);
            unset($item["city_id"]);
            unset($item["id"]);
            unset($item["remark"]);
            unset($item["created_at"]);
            unset($item["updated_at"]);
            unset($item["flag"]);
        }
        $data["staff_fee"] =$staff_fee;
        $data["service_fee"] =$service_fee;
        $data["achievement_fee"] =$achievement_fee;
        $data["total_fee"] = $total_fee;
        $data["category_name"] =$this->getCategoryNamesByID($supcategory_id,$subcategory_id,$level);
        unset($data["desc"]);
//        unset($data["standrad"]);
        unset($data["process"]);
//        unset($data["material"]);
        unset($data["staffitems"]);
        unset($data["id"]);
        unset($data["supcategory_id"]);
        unset($data["subcategory_id"]);
        unset($data["level"]);
        unset($data["province_id"]);
        unset($data["city_id"]);
        unset($data["work_price_id"]);
        unset($data["show_order"]);
        unset($data["created_at"]);
        unset($data["updated_at"]);
        unset($data["flag"]);
        return $data;
    }

    public function getMutilQuotaByIdAndLevel($opt){
        $opt_arr = explode(',',$opt);
        if(empty($opt_arr)){
            throw new RoException(RoError::OPT_REQUIRED);
        }
        $ret = ['standrads'=>[],'materials'=>[],'items'=>[],'staff_fee'=>null,'service_fee'=>null,'achievement_fee'=>null,'total_fee'=>null,'category_names'=>[]];
        $_tmp_arr = [];
        $staff_fee = 0;
        $service_fee = 0;
        $service_fee_arr = array();
        $service_fee_num_arr = array();
        $achievement_fee = 0;
        $achievement_fee_arr = array();
        $achievement_fee_num_arr = array();
        $person_num = 0;
        $service_num = 0;
        $achievement_num = 0;
        foreach ($opt_arr as $k=>$o){
             $o_arr = explode("-",$o);
             $supcategory_id = $o_arr[0];
             $subcategory_id = $o_arr[1];
             $level = $o_arr[2];
            if(empty($supcategory_id) || empty($subcategory_id) || empty($level)){
                throw new RoException(RoError::OPT_REQUIRED);
            }
            $where = [
                ["supcategory_id","=",$supcategory_id],
                ["subcategory_id","=",$subcategory_id],
                ["level","=",$level]
            ];
            $fields = ["desc","standrad","process","material","scope"];
            $data = Quota::where($where)->select(["*"])->first();
            if(!$data){
                throw new CategoryException(CategoryError::CATEGORY_NOT_EXSITS);
            }
            $ret['standrads'][$k] = $data['standrad'];
            $ret['materials'][$k] = $data['material'];
            $ret["category_names"][$k] =$this->getCategoryNamesByID($supcategory_id,$subcategory_id,$level);
            foreach ($data->staffitems as $item) {
                $item["fee_alias"] = empty($item["fee_alias"]) ? $item["fee_name"] : $item["fee_alias"];
                $_key =$item['fee_name'].'_'.$item['fee_alias'];
                if($item["type"] == 0 && !array_key_exists($_key,$_tmp_arr)){
                    $_staff_fee = round(floatval($item["fee_price"])*$item["fee_num"],2);
                    $_staff_fee_max = isset($_tmp_arr[$_key]) && !empty($_tmp_arr[$_key]) ? $_tmp_arr[$_key] : 0;
                    if($_staff_fee > $_staff_fee_max) {
                        $_tmp_arr[$_key] = $_staff_fee;
                        $staff_fee += $_staff_fee - $_staff_fee_max;
                        $ret['items']['person'][$item["fee_name"]][$_key]['type']          = "人员费用";
                        $ret['items']['person'][$item["fee_name"]][$_key]['fee_name']     = $item["fee_name"];
                        $ret['items']['person'][$item["fee_name"]][$_key]['fee_alias']    = $item["fee_alias"] ;
                        $ret['items']['person'][$item["fee_name"]][$_key]['fee_num']      = $item["fee_num"];
                        $ret['items']['person'][$item["fee_name"]][$_key]['fee_price']    = $item["fee_price"];
                        $ret['items']['person'][$item["fee_name"]][$_key]['item_total']   = $_staff_fee;
                        $person_num++;
                    }
                }
                if($item["type"] == 1){
                    if($service_fee >= 7 ){
                        $_service_fee = 1.5;
                        $service_fee += $_service_fee;
                    }else {
                        $_service_fee = round(floatval($item["fee_price"]) * $item["fee_num"], 2);
                        $service_fee += $_service_fee;
                    }
                    if(!isset( $service_fee_arr[$_key]) ){
                        $service_num++;
                    }
                    $service_fee_arr[$_key] = isset( $service_fee_arr[$_key]) ? $service_fee_arr[$_key] + $_service_fee : $_service_fee;
                    $service_fee_num_arr[$_key] = isset( $service_fee_num_arr[$_key]) ? $service_fee_num_arr[$_key] + $item["fee_num"] :  $item["fee_num"];
                    $ret['items']['service'][$item["fee_name"]][$_key]['type']           = "服务费用";
                    $ret['items']['service'][$item["fee_name"]][$_key]['fee_name']      = $item["fee_name"];
                    $ret['items']['service'][$item["fee_name"]][$_key]['fee_alias']     = $item["fee_alias"] ;
                    $ret['items']['service'][$item["fee_name"]][$_key]['fee_num']       =  $service_fee_num_arr[$_key] ;
                    $ret['items']['service'][$item["fee_name"]][$_key]['fee_price']     = $service_fee_arr[$_key];
                    $ret['items']['service'][$item["fee_name"]][$_key]['item_total']    = $service_fee_arr[$_key];
                }
                if($item["type"] == 2){
                    $_achievement_fee = round(floatval($item["fee_price"])*$item["fee_num"],2);
                    $achievement_fee += $_achievement_fee;
                    if(!isset( $achievement_fee_arr[$_key]) ){
                        $achievement_num++;
                    }
                    $achievement_fee_arr[$_key] = isset( $achievement_fee_arr[$_key]) ? $achievement_fee_arr[$_key] + $_achievement_fee : $_achievement_fee;
                    $achievement_fee_num_arr[$_key] = isset( $achievement_fee_num_arr[$_key]) ? $achievement_fee_num_arr[$_key] + $item["fee_num"] :  $item["fee_num"];
                    $ret['items']['achievement'][$item["fee_name"]][$_key]['type']          = "业绩费用";
                    $ret['items']['achievement'][$item["fee_name"]][$_key]['fee_name']     = $item["fee_name"];
                    $ret['items']['achievement'][$item["fee_name"]][$_key]['fee_alias']    = $item["fee_alias"] ;
                    $ret['items']['achievement'][$item["fee_name"]][$_key]['fee_num']      = $achievement_fee_num_arr[$_key] ;
                    $ret['items']['achievement'][$item["fee_name"]][$_key]['fee_price']    = $achievement_fee_arr[$_key];
                    $ret['items']['achievement'][$item["fee_name"]][$_key]['item_total']   = $achievement_fee_arr[$_key];
                }
            }
        }
        $ret['staff_fee'] = $staff_fee;
        $ret['service_fee'] = $service_fee;
        $ret['achievement_fee'] = $achievement_fee;
        $ret['person_num'] = $person_num;
        $ret['service_num'] = $service_num;
        $ret['achievement_num'] = $achievement_num;
        $ret['total_fee'] = round($staff_fee+$service_fee+ $achievement_fee,2);
        return $ret;

    }

    /**
     * @param $cateid
     * 通过二级资质id 获取对应的资质办理标准详情,如果该资质含有等级,把所有等级的数据都返回
     */
    public function getStandardDetailById($supcateid,$subcateId){

        $where = [
            ["supcategory_id","=",$supcateid],
            ["subcategory_id","=",$subcateId],

        ];
        $fields = ["id","desc","standrad","process","material","scope","level"];
        $data = Quota::where($where)->select($fields)->orderBy("level",'asc')->get();
        if($data->isEmpty()){
            throw new CategoryException(CategoryError::CATEGORY_NOT_EXSITS);
        }
        $standrad = [];
        $scope = [];
        $title = $this->getSubCategoryNameById($subcateId);
        $levels = $title."专业资质分为";
        $ids = [];
        foreach ($data as $item){
            $standrad_item = [];
            $scope_item = [];
            $ids[] = $item['id'];
            $levels.=$this->getLevelNameById($item['level']);
            $standrad_item['sub_title']= $this->getLevelNameById($item['level'])."办理标准";
            $standrad_item['content'] = $item['standrad'];
            $scope_item['sub_title']= $this->getLevelNameById($item['level'])."办理范围";
            $scope_item['content'] = $item['scope'];
            array_push($standrad,$standrad_item);
            array_push($scope,$scope_item);
        }
        sort($ids);
        if(count($ids) == 1){
            $last_id = Quota::where('id', '<', $ids)->max('id');
            $next_id = Quota::where('id', '>', $ids)->min('id');
        }else{
            $last_id = Quota::where('id', '<', array_pop($ids))->max('id');
            $next_id = Quota::where('id', '>', array_shift($ids))->min('id');
        }




        $last_news = Quota::where('id', '=', $last_id)->select(["supcategory_id","subcategory_id"])->first();
        $last_news['title'] = $this->getSubCategoryNameById($last_news['subcategory_id']);

        $next_news = Quota::where('id', '=', $next_id)->select(["supcategory_id","subcategory_id"])->first();
        $next_news['title'] = $this->getSubCategoryNameById($next_news['subcategory_id']);
        if($last_news ==null){
            $last_news["supcategory_id"] = 0;
            $last_news["subcategory_id"] = 0;
            $last_news["title"] = "没有上一条了";

        }
        if($next_news ==null){
            $next_news["supcategory_id"] = 0;
            $next_news["subcategory_id"] = 0;
            $next_news["title"] = "没有下一条了";

        }
        $recommend = Quota::where("flag","=",1)->select(["supcategory_id","subcategory_id"])->orderBy(\DB::raw('RAND()'))->take(2)->get();
        foreach ($recommend as &$rec){
            $rec['title'] = $this->getSubCategoryNameById($rec['subcategory_id']);
        }
        $ret = [
            'title'=>$title,
            'key_words'=>$title,
            'desc'=>$levels,
            'standrad'=>$standrad,
            'scope'=>$scope,
            'last_news'=>$last_news,
            'next_news'=>$next_news,
            'recommend'=>$recommend

        ];
        return $ret;
    }


    public function getCategoryNamesByID($supcateid,$subcateId,$level){
        $where = [
            ["id","=",$subcateId],
            ["flag","=",1]
        ];
        $fileds = ["id","category_name","parent_cate_id","level"];
        $data = SecQualifyCategory::where($where)->select($fileds)->first();
        $data = $data->toArray();
        $subcatename = $data['category_name'];
        $where_sup = [
            ["id","=",$data['parent_cate_id']],
            ["flag","=",1]
        ];
        $supcatename = SupQualifyCategory::where($where_sup)->select(["category_name"])->first();
        if($supcatename){
            $supcatename = $supcatename->toArray()["category_name"];
        }
//        switch ($level){
//            case  1 : $level_name = "一级";break;
//            case  2 : $level_name = "二级";break;
//            case  3 : $level_name = "三级";break;
//            case 4  :  $level_name = "A级";break;
//            case 5 :$level_name = "B级";break;
//            case 6 :$level_name = "C级";break;
//            case 7 :$level_name = "甲级";break;
//            case 8 :$level_name = "乙级";break;
//            case 9 :$level_name = "丙级";break;
//            case 10 :$level_name = "无分级";break;
//            default:$level_name = "无分级";break;
//        }
        $level_name = $this->getLevelNameById($level);
        return $supcatename."-".$subcatename."-".$level_name;
    }
    function getlevelsSubCateQuotaList($subCateId){
        $where = [
            ["subcategory_id","=",$subCateId],
            ["flag","=",1]
        ];
        $data = Quota::where($where)->select(["*"])->get();
        $ret = [];
        if($data){
            foreach ($data as &$item){
                $tmp = [];
                $tmp["level_id"] = $item["level"];
                $tmp["category_name"] = $this->getFullNamefromCate($item['subcategory_id'],$item["level"]);
                $tmp["fee_list"] =  $this->getFeeList($item->staffitems);
                array_push($ret,$tmp);
            }
        }

        return $ret;

    }
    public function getFullNamefromCate($category_id,$level){
        $where = [
            ["id","=",$category_id],
            ["flag","=",1]
        ];
        $fileds = ["id","category_name","parent_cate_id"];
        $data = SecQualifyCategory::where($where)->select($fileds)->first();
        $data = $data->toArray();
        $subcatename = $data['category_name'];
        $where_sup = [
            ["id","=",$data['parent_cate_id']],
            ["flag","=",1]
        ];
        $supcatename = SupQualifyCategory::where($where_sup)->select(["category_name"])->first();
        if($supcatename){
            $supcatename = $supcatename->toArray()["category_name"];
        }
        $level_name = $this->getLevelNameById($level);
        return $supcatename."-".$subcatename."-".$level_name;



    }
    public function getLevelNameById($id){
        $where = [
            ['id','=',$id]
        ];
        $name = "";
        $fields = ["name"];
        $level = Level::where($where)->select($fields)->first();
        if($level){
            return $level["name"];
        }
        return $name;

    }
    public function getFeeList($fee){
        $fee_list = [];
        if($fee){
            foreach ($fee as $item){
                $tmp = [];
                switch ($item["type"]){
                    case 0:$type = "人员费用";break;
                    case 1:$type = "服务费用";break;
                    case 2:$type = "业绩费用";break;
                    default:$type = "其他费用";break;
                }
                $tmp["type"]  = $type;
                $tmp["fee"] = floatval($item["fee_price"])*$item["fee_num"];
                $tmp["fee"] = sprintf("%.2f", $tmp["fee"]);
                $flag = 0;
                if($fee_list){
                    foreach ($fee_list as &$fee_item){
                        if($tmp["type"] == $fee_item["type"]){

                            $fee_item["fee"] = $fee_item["fee"]+$tmp["fee"];
                            $fee_item["fee"] = sprintf("%.2f", $fee_item["fee"]);
                            $flag = 1;
                        }
                    }
                }
                if($flag == 0){
                    array_push($fee_list,$tmp);
                }

            }
            $total = 0;
            if($fee_list){
                foreach ($fee_list as $item){
                    $total = $total+$item["fee"];
                }
            }

            $tmp["type"] = "总费用";
            $tmp["fee"] = $total;
            array_push($fee_list,$tmp);
        }

        return $fee_list;

    }
    public function getSubCategoryNameById($id){
        $data = SecQualifyCategory::where('id',$id)->select(['category_name'])->first();
        if($data == null){
            return "";
        }else{
            return $data['category_name'];
        }
    }

}